'use strict';

const Service = require('egg').Service;

class BaseService extends Service {
  constructor(ctx, model) {
    super(ctx);
    this.model = model;
  }

  // 查询列表
  async findAll(params) {
    const { page = 1, pageSize = 10, ...query } = params;
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);

    const { count, rows } = await this.model.findAndCountAll({
      where: query,
      offset,
      limit,
      order: [['created_at', 'DESC']],
    });

    return {
      list: rows,
      pagination: {
        total: count,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    };
  }

  // 查询单个
  async findById(id) {
    const result = await this.model.findByPk(id);
    if (!result) {
      this.ctx.throw(404, '记录不存在');
    }
    return result;
  }

  // 创建
  async create(data) {
    return await this.model.create(data);
  }

  // 更新
  async update(id, data) {
    const record = await this.findById(id);
    return await record.update(data);
  }

  // 删除
  async destroy(id) {
    const record = await this.findById(id);
    return await record.destroy();
  }
}

module.exports = BaseService; 